﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Common
{
    public class Export
    {
        public void ExportExcel(DataTable dt,string[] titleArray)
        {
            //设置导出文件路径
            string path = "D:/Export/";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            //设置新建文件路径及名称
            string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlxs";

            //创建文件
            FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);

            //以指定的字符编码向指定的流写入字符
            StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));

            StringBuilder strbu = new StringBuilder();

            //写入标题
            for (int i = 0; i < titleArray.Length; i++)
            {
                strbu.Append(titleArray[i].ToString() + "\t");
            }
            //加入换行字符串
            strbu.Append(Environment.NewLine);

            //写入内容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    strbu.Append(dt.Rows[i][j].ToString() + "\t");
                }
                strbu.Append(Environment.NewLine);
            }

            sw.Write(strbu.ToString());
            sw.Flush();
            file.Flush();

            sw.Close();
            sw.Dispose();

            file.Close();
            file.Dispose();

            MessageBox.Show("搞完");
        }
    }
}
